<template>
  <div ref="canvas"></div>
</template>

<script lang="ts" setup>
import * as THREE from 'three';
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { ref, onMounted } from "vue";

const radius = 300;
let mixer = null;
let anima = null;
const clock = new THREE.Clock();
// 画布
const canvas = ref<any>('');
// 场景
const scene = new THREE.Scene();
// 相机
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 2000);
camera.position.set(100, 100, 1000);
camera.lookAt(0, 0, 0);
// 光源
const light = new THREE.HemisphereLight(0xffffff);
light.position.set(0, 0, 200);
scene.add(light);
// 分组
const global = new THREE.Group();
global.name = '地球';
const movementPoint = new THREE.Group();
movementPoint.name = '运动的点';
scene.add(global, movementPoint);
// 几何体
const globalGeometry = new THREE.SphereGeometry(radius, 100, 100);
// 地球贴图
const globalTexture = new THREE.TextureLoader().load(new URL("../assets/globalMap.jpg", import.meta.url).href);
// 材质
const globalMaterial = new THREE.MeshLambertMaterial({
  map: globalTexture,
  transparent: true,
  opacity: 1,
  side: THREE.DoubleSide,
});
// 网格模型Mesh
const globalMesh = new THREE.Mesh(globalGeometry, globalMaterial);
global.add(globalMesh);
// 渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true,
});
renderer.setClearColor(0xffffff);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
// 相机控件
const orbitControl = new OrbitControls(camera, renderer.domElement);
orbitControl.update();

onMounted(() => {
  canvas.value.appendChild(renderer.domElement);
  animate();
});

// 动画
function animate() {
  renderer.render(scene, camera);
  anima = requestAnimationFrame(animate);
  let time = clock.getDelta();
  global.rotateY((time * Math.PI) / 8);
  mixer.update(time);
}

/**
 * 求两个向量的中点
 * @param v1
 * @param v2
 */
function getVCenter(v1: THREE.Vector3, v2: THREE.Vector3) {
  const v = v1.add(v2);
  return v.divideScalar(2);
}

/**
 *
 * @param v1
 * @param v2
 * @param len
 */
function getLenVector(v1: THREE.Vector3, v2: THREE.Vector3, len) {
  let v1v2Len = v1.distanceTo(v2);
  return v1.lerp(v2, len / v1v2Len);
}
/**
 * 经纬度转为坐标
 */
function convert(longitude, latitude, radius = 300) {
  const lg = THREE.MathUtils.degToRad(longitude);
  const lt = THREE.MathUtils.degToRad(latitude);
  const temp = radius * Math.cos(lt);
  const x = temp * Math.sin(lg);
  const y = radius * Math.sin(lt);
  const z = temp * Math.cos(lg);
  return new THREE.Vector3(x, y, z);
}

</script>
